package com.boilermaker.lotterysystem.service.statusconvert.operator;

import com.boilermaker.lotterysystem.dao.dataobject.ActivityPrizeDO;
import com.boilermaker.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.boilermaker.lotterysystem.service.dto.ConvertStatusDTO;
import com.boilermaker.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.boilermaker.lotterysystem.service.enums.ActivityUserStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class PrizeStatusOperator extends AbstractStatusOperator {

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean convertPolicy(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        Long prizeId = dto.getPrizeId();
        ActivityPrizeStatusEnum targetStatus = dto.getTargetPrizeStatus();

        if (activityId == null || prizeId == null || targetStatus == null) {
            return false;
        }

        ActivityPrizeDO activityPrizeDO =
                activityPrizeMapper.selectByActivityIdAndPrizeId(activityId, prizeId);

        // 若原状态与目标状态一致，则不能转换
        return activityPrizeDO != null
                && !activityPrizeDO.getStatus().equalsIgnoreCase(targetStatus.name());
    }

    @Override
    public Boolean convert(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        Long prizeId = dto.getPrizeId();
        ActivityUserStatusEnum targetStatus = dto.getTargetUserStatus();

        try {
            activityPrizeMapper.updateStatus(activityId, prizeId, targetStatus.name());
            return true;
        } catch (Exception e) {
            log.error("状态转换异常", e);
            return false;
        }
    }
}
